<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户端1</title>
</head>
<body>

<label>房间名:</label>
<input type="text" id="txtRoom"/>
<button type="button" id="btn-joinRoom">加入房间</button>
<button type="button" id="btn-leaveRoom">离开房间</button>
<br/>

<label>聊天内容:</label><br/>
<textarea id="content" style="height: 200px; width:300px;"></textarea>
<br/>
<input  id="sendMsg" type="text"/>
<button id="btn_send">发送</button>

<!-- 首先引入 socket.io 客户端脚本-->
<script src="./js/socket.js"></script>
<script type="text/javascript">
    var socket = io('http://localhost:3000');
        // 监听 receiveMsg 事件，用来接收其他客户端推送的消息
        socket.on("receiveMsg",function (data) {
            content.value+=data.client+":"+data.msg+"\r\n";
        });

    var content=document.getElementById("content");
    var sendMsg=document.getElementById("sendMsg");
    var btn_send=document.getElementById("btn_send");
    var btn_joinRoom=document.getElementById("btn-joinRoom");
    var btn_leaveRoom=document.getElementById("btn-leaveRoom");
    var txtRoom=document.getElementById("txtRoom");

    btn_leaveRoom.addEventListener("click",function () {
        socket.emit("leaveRoom",{"roomName":txtRoom.value},function (data) {
            //打印离开房间后服务端返回的信息
            console.log("离开房间："+ JSON.stringify(data) )
        });
        txtRoom.value="";
    })
    btn_joinRoom.addEventListener("click",function () {
        var roomName=txtRoom.value;
        socket.emit("joinRoom",{"roomName":roomName},function (data) {
            //打印加入房间成功后返回的信息
            console.log("加入房间："+JSON.stringify(data));
        })
    });
    btn_send.addEventListener("click",function () {
        if(!sendMsg.value){
            alert("请输入房间号");return;
        }
        var data={"msg":sendMsg.value,"roomName":txtRoom.value,"client":"客户端1"};
        //给服务端发送 sendMsg事件名的消息
        socket.emit("sendMsg",data,function (data) {
            //打印消息发送成功后服务端返回的信息
            console.log("消息发送："+JSON.stringify(data));
        });
        content.value+=data.client+":"+data.msg+"\r\n";
        sendMsg.value="";
    });

</script>

</body>
</html>